﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CMS.Domain
{
    public class HtmlPublisher
    {
        public static HtmlPublisher Instance = new HtmlPublisher();

        public bool IsBusy { get; private set; }

        public void Push(object data, string htmlFile, string templateFile)
        {
            if(!File.Exists(templateFile))
            {
                return;
            }

            FileInfo htmlFileInfo = new FileInfo(htmlFile);
            if(htmlFileInfo.Directory.Exists == false)
            {
                htmlFileInfo.Directory.Create();
            }

            string templateText = File.ReadAllText(templateFile);

            // 找到需要替换的标记
            MatchCollection matches = new Regex("\\$(?<flag>[^\\$\\r\\n,\\(\\)]*)\\$").Matches(templateText);

            List<string> flags = new List<string>();
            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    Insert(flags, match.Groups[1].Value);
                }
            }

            foreach (string flag in flags)
            {
                Regex regex = new Regex(string.Format("\\${0}\\$",flag));
                templateText = regex.Replace(templateText, GetValueString(data, flag));
            }

            File.WriteAllText(htmlFile, templateText);
        }

        private void Insert(List<string> list, string item)
        {
            for (int index = 0; index < list.Count; index++)
            {
                if(string.Equals(list[index], item))
                {
                    return;
                }
            }
            list.Add(item);
        }

        private string GetValueString(object obj, string propertyName)
        {
            Type type = obj.GetType();
            PropertyInfo property = type.GetProperty(propertyName);
            if(property !=null)
            {
                return property.GetValue(obj).ToString();
            }
            FieldInfo field = type.GetField(propertyName);
            if (field != null)
            {
                return field.GetValue(obj).ToString();
            }
            return null;
        }
    }
}
